
package com.jootu.cc.ccapi;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jootu.cc.ccapi.domain.UserInfoMapper;
import com.jootu.cc.ccapi.shiro.UserInfo;


/**
* @ClassName: MyShiroRealm
* @Description: TODO(认证信息.(身份验证) : Authentication 是用来验证用户身份)
* @author antch,861710865@qq.com
* @date 2017年8月14日 下午11:26:49
* 
*/

public class MyShiroRealm extends  AuthorizingRealm {

	@Autowired
	private UserInfoMapper userInfoMapper;
	
    private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

    /*
     *登录认证的方法
     *认证信息.(身份验证) : 
     *Authentication 是用来验证用户身份
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		logger.info("身份认证方法-----" + this.getClass().getName() + ".doGetAuthenticationInfo");
		String userName = (String) token.getPrincipal();
		logger.info("输入账号：：" + userName);
		logger.info("token.getCredentials():" + token.getCredentials());
		//通过username从数据库中查找 User对象，如果找到，没找到.
	    //实际项目中，这里可以根据实际情况做缓存，如果不做，
		//Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
		UserInfo userInfo = userInfoMapper.findByUserName(userName);
		
		logger.info("查找到用户：" + userInfo);
		
		if(null == userInfo) {
			return null;
		}
		
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				 userInfo, //用户名
		            userInfo.getPassword(), //密码
		            ByteSource.Util.bytes(userInfo.getState()),//salt=username+salt
		            getName()  //realm name
				);
		
		return authenticationInfo;
	}

	/*
	 *链接权限的实现
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		logger.info("权限配置：：MyShiroRealm。doGetAuthorizationInfo（）");

//		SimpleAuthorizationInfo authorizationInfo =
//				new SimpleAuthorizationInfo();
//		UserInfo userInfo
		return null;
	}


}
